package com.dxy.chatserver.subscription;

import com.aliyun.openservices.ons.api.batch.BatchMessageListener;
import com.aliyun.openservices.ons.api.bean.BatchConsumerBean;
import com.aliyun.openservices.ons.api.bean.Subscription;
import com.dxy.chatserver.builder.RocketBuilder;
import com.dxy.chatserver.config.ChatMsgConfig;
import com.dxy.chatserver.config.ChatMsgRocketConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 聊天服务订阅
 *
 * @author: none
 * @date: 2021/12/21
 **/
@EnableConfigurationProperties({ChatMsgRocketConfig.class, ChatMsgConfig.class})
@Configuration
@Slf4j
public class SubscriptionConfiguration {

    @Resource
    private ChatMsgRocketConfig config;

    @Resource
    private ChatMsgConfig chatMsgConfig;

    @Resource
    private MsgBatchListener msgBatchListener;
    /**
     * rocket mq 消费者
     *
     * @return
     */
    @Bean(initMethod = "start", destroyMethod = "shutdown")
    public BatchConsumerBean consumer() {
        if(!config.getChatMsg().getConsumerMsg()){
            return null;
        }
        BatchConsumerBean consumerBean = new BatchConsumerBean();
        consumerBean.setProperties(RocketBuilder.properties(config.getChatMsg().getAccessKey(), config.getChatMsg().getSecretKey(), config.getChatMsg().getNameServiceAddress(), config.getChatMsg().getConsumeThreadNums(), chatMsgConfig.getOnlineMsgGroup(), chatMsgConfig.getOnlineMsgMessageModel()));
        Map<Subscription, BatchMessageListener> subscriptionTable = new HashMap<>();
        Subscription subscription = new Subscription();
        subscription.setTopic(chatMsgConfig.getOnlineMsgTopic());
        subscriptionTable.put(subscription, msgBatchListener);
        // 订阅多个topic如上面设置
        consumerBean.setSubscriptionTable(subscriptionTable);
        log.info("聊天信息存储服务启动!");
        return consumerBean;
    }

}
